package com.bupt.smart.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bupt.smart.application.CustomApplication;
import com.bupt.smart.model.User;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.smart.R;
import com.bupt.smart.utils.CheckNetwork;
import com.bupt.smart.utils.Constants;
import com.bupt.smart.utils.MD5Util;
import com.bupt.smart.utils.SaveSharedPreference;
import com.bupt.smart.utils.ValidateUserInfo;

import java.net.HttpURLConnection;
import java.util.Set;

import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressFlower;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private AutoCompleteTextView mTelView;
    private EditText mPasswordView;
    private TextView mForgetTxtView, mCreateTxtView;

    private ACProgressFlower dialog;

    private Button mLoginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //初始化view
    private void initView() {
        mTelView = (AutoCompleteTextView) findViewById(R.id.txt_tel);
        mPasswordView = (EditText) findViewById(R.id.txt_password);
        mForgetTxtView = (TextView) findViewById(R.id.txt_forgot);
        mCreateTxtView = (TextView) findViewById(R.id.txt_create);
        dialog = new ACProgressFlower.Builder(this)
                .direction(ACProgressConstant.DIRECT_CLOCKWISE)
                .themeColor(Color.WHITE)
                .text("登录中")
                .fadeColor(Color.DKGRAY).build();
        mLoginButton = (Button) findViewById(R.id.tel_sign_in_button);

        //???
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        mForgetTxtView.setOnClickListener(this);
        mCreateTxtView.setOnClickListener(this);
        mLoginButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String tel = mTelView.getText().toString();

        //根据被点击的view id确定要进行的操作
        switch (v.getId()) {
            case R.id.tel_sign_in_button:
                attemptLogin();
                break;
            case R.id.txt_create:
                Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
                intentRegister.putExtra(Constants.TAG_TEL, tel);
                startActivity(intentRegister);
                //finish();
                break;
            case R.id.txt_forgot:
                Intent intentForgot = new Intent(LoginActivity.this, ForgotPassActivity.class);
                intentForgot.putExtra(Constants.TAG_TEL, tel);
                startActivity(intentForgot);
                //finish();
                break;
        }
    }

    //尝试发起登录请求
    private void attemptLogin() {
        // Reset errors.
        mTelView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String tel = mTelView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // 检查手机号合法性
        if (TextUtils.isEmpty(tel)) {
            mTelView.setError(getString(R.string.error_field_required));
            focusView = mTelView;
            cancel = true;
        } else if (!ValidateUserInfo.isTelValid(tel)) {
            mTelView.setError(getString(R.string.error_invalid_tel));
            focusView = mTelView;
            cancel = true;
        }

        // 检查密码是否为空
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        }

        if (cancel) {
            //存在错误，取消登录，将屏幕焦点设置为出错的位置
            focusView.requestFocus();
        } else {
            if (!CheckNetwork.isConnected(LoginActivity.this)) {
                Toast.makeText(LoginActivity.this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
            } else {
                //启动异步任务进行登录操作
                try {
                    password = MD5Util.md5Encode(password);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Call<User> call = APIManager.getUserAPI().login(tel, password);
                dialog.show();
                call.enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        dialog.dismiss();
                        Toast.makeText(LoginActivity.this, response.code() + "", Toast.LENGTH_SHORT).show();
                        if (response.body() != null) {
                            ((CustomApplication) getApplication()).setUserInfo(response.body());
                            setAlias();
                            SaveSharedPreference.setUserInfo(LoginActivity.this.getApplicationContext(), response.body());
                            SaveSharedPreference.setUserLoginStatus(LoginActivity.this.getApplicationContext(), true);
                            Toast.makeText(LoginActivity.this,  ((CustomApplication) getApplication()).getUserInfo().getUserID() + "", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(LoginActivity.this, TabActivity.class));
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, "empty user info", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        dialog.dismiss();
                        mPasswordView.setError(getString(R.string.error_incorrect_password));
                        mPasswordView.requestFocus();
                    }
                });
            }
        }
    }

    //设置极光推送的用户别名
    private void setAlias() {
        String phone = ((CustomApplication) getApplication()).getUserInfo().getPhone();
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, String.valueOf(phone)));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    System.out.println("Set tag and alias success");
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    System.out.println("Failed to set alias and tags due to timeout. Try again after 60s.");
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    System.out.println("Failed with errorCode = " + code);
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    System.out.println("Unhandled msg - " + msg.what);
            }
        }
    };
}
